<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container>
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail" layout="horizontal">
        <a-row :span="24">
          <a-col :span="24">
            <a-row :gutter="10">
              <a-col :span="1">
                <h4>包装材料</h4>
              </a-col>
            </a-row>
<!--            <a-button type="primary" icon="" size="small"> 包装材料 </a-button>
            <erp-goods-list-model
              ref="selectGoodsList"
              :modalWidth="modalWidth"
              :category="category"
              @goodsOk="goodsOk"
              checkval="checkbox"
            >
            </erp-goods-list-model>-->
          </a-col>
          <a-col :span="24">
            <!-- 表格 -->
            <a-table
              bordered
              class="mytable"
              :scroll="{ x: 1300, y: 100 }"
              :data-source="model.erpGoodsPackageList"
              :columns="warpMaterial.columns"
              :rowKey="(record) => record.rowKey"
              :pagination="false"
            >
              <template slot="number" slot-scope="text, record">
                <edit-number-cell-2
                  :disabled="formDisabled && packageDisabled"
                  :text="text"
                  @change="onCellChange(record, 'number', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="grams" slot-scope="text, record">
                <edit-number-cell-2
                  :disabled="formDisabled && packageDisabled"
                  :text="text"
                  @change="onCellChange(record, 'grams', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="packageArea1" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && packageDisabled"
                  @change="onCellChange(record, 'packageArea1', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="packageArea2" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && packageDisabled"
                  @change="onCellChange(record, 'packageArea2', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="innerPackageArea" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && packageDisabled"
                  @change="onCellChange(record, 'innerPackageArea', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="packageNumber1" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && packageDisabled"
                  @change="onCellChange(record, 'packageNumber1', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="packageUnitPrice1" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && packageDisabled"
                  @change="onCellChange(record, 'packageUnitPrice1', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="packageNumber2" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && packageDisabled"
                  @change="onCellChange(record, 'packageNumber2', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="packageUnitPrice2" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && packageDisabled"
                  @change="onCellChange(record, 'packageUnitPrice2', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="innerPackageNumber" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && packageDisabled"
                  @change="onCellChange(record, 'innerPackageNumber', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="innerPackageUnitPrice" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && packageDisabled"
                  @change="onCellChange(record, 'innerPackageUnitPrice', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="otherPackageCost" slot-scope="text, record">
                <edit-number-cell-2
                  :disabled="formDisabled && packageDisabled"
                  :text="text"
                  @change="onCellChange(record, 'other', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="operation" slot-scope="text, record">
                <a-popconfirm title="确认删除?" @confirm="() => onDelete(record.id)">
                  <a href="javascript:;">删除</a>
                </a-popconfirm>
                <!--                <a @click="handleEdit(record)">保存</a>-->
              </template>
            </a-table>
          </a-col>
        </a-row>
        <a-row :span="24">
          <a-col :span="24">
<!--            <a-button type="primary" icon="" size="small"> 产品报价 </a-button>-->
            <a-row :gutter="10">
              <a-col :span="1">
                <h4>产品报价</h4>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="24">
            <a-table
              bordered
              class="mytable"
              :data-source="model.productQuotationList"
              :columns="productQuote.columns"
              :scroll="{ x: 1300, y: 100 }"
              :rowKey="(record) => record.rowKey"
              :pagination="false"
            >
              <template slot="packageSpec" slot-scope="text, record">
                <!-- <a-input type="number" :value="text" @blur="onProductCellChange(record, 'packageSpec', $event)" /> -->
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && packageDisabled"
                  @change="onProductCellChange(record, 'packageSpec', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="packageMethod" slot-scope="text, record">
                <a-select
                  :disabled="formDisabled && packageDisabled"
                  :value="text"
                  @change="onProductCellChange(record, 'packageMethod', $event)"
                >
                  <a-select-option
                    v-for="item in packageMethodOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </template>
              <template slot="codingFee" slot-scope="text, record">
                <a-select
                  :disabled="formDisabled && financeDisabled && packageDisabled"
                  :value="text"
                  @change="onProductCellChange(record, 'codingFee', $event)"
                >
                  <a-select-option
                    v-for="item in codingFeeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </template>
              <template slot="midExpenses" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && financeDisabled"
                  @change="onProductCellChange(record, 'midExpenses', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="landFreight" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && financeDisabled"
                  @change="onProductCellChange(record, 'landFreight', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="adhesiveStickers" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && financeDisabled"
                  @change="onProductCellChange(record, 'adhesiveStickers', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="other" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && financeDisabled"
                  @change="onProductCellChange(record, 'other', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="seaFreight" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && financeDisabled"
                  @change="onProductCellChange(record, 'seaFreight', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="cocoExpenses" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && financeDisabled"
                  @change="onProductCellChange(record, 'cocoExpenses', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="royalty" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && financeDisabled"
                  @change="onProductCellChange(record, 'royalty', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="insurancePremium" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && financeDisabled"
                  @change="onProductCellChange(record, 'insurancePremium', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="printingFee" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && financeDisabled"
                  @change="onProductCellChange(record, 'printingFee', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="commission" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && financeDisabled"
                  @change="onProductCellChange(record, 'commission', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="other2" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && financeDisabled"
                  @change="onProductCellChange(record, 'other2', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="ywDamageTon" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && financeDisabled"
                  @change="onProductCellChange(record, 'ywDamageTon', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="ywTonPrice" slot-scope="text, record">
                <edit-number-cell-2
                  :text="text"
                  :disabled="formDisabled && financeDisabled"
                  @change="onProductCellChange(record, 'ywTonPrice', $event)"
                ></edit-number-cell-2>
              </template>
              <template slot="ywisCompliantPolicies" slot-scope="text">
                <span v-if="text == '1'">是</span>
                <span v-else>否</span>
              </template>
              <template slot="operation" slot-scope="text, record">
                <a-popconfirm title="确认删除?" @confirm="() => onDeleteProduct(record.id)">
                  <a href="javascript:;">删除</a>
                </a-popconfirm>
              </template>
            </a-table>
          </a-col>
        </a-row>
        <a-row :span="24" style="margin: 4px">
          <a-col :span="12">
            <a-form-model-item label="报价备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="quotationRemarks">
              <a-textarea
                :disabled="formDisabled && starterDisabled"
                v-model="model.quoteRemark"
                placeholder=""
                :rows="4"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="财务备录" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="financialRemarks">
              <a-textarea
                :disabled="formDisabled && starterDisabled"
                v-model="model.financeRemark"
                placeholder=""
                :rows="4"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
<!--        <a-row :span="24" style="margin: 4px">
          <a-col :span="4">
            <a-form-model-item label="汇率" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="exchangeRate">
              <a-input-number
                v-model="model.exchangeRate"
                placeholder="请输入汇率"
                @blur="calcAllFees"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-form-model-item label="税率" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taxRate">
              <a-input-number v-model="model.rate" placeholder="请输入税率" @blur="calcAllFees" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="客户其他费用(如版费等)"
              :labelCol="labelCol3"
              :wrapperCol="wrapperCol3"
              prop="otherExpenses"
            >
              <a-input-number
                :disabled="formDisabled && starterDisabled"
                v-model="model.otherExpenses"
                placeholder="请输入客户其他费用(如版费等)"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="客户其他费用说明"
              :disabled="formDisabled && starterDisabled"
              :labelCol="labelCol3"
              :wrapperCol="wrapperCol3"
              prop="otherRemarks"
            >
              <a-input v-model="model.otherExpensesDes" placeholder="请输入客户其他费用说明"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-form-model-item label="总金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="totalAmount">
              <a-input-number v-model="model.totalAmount" placeholder="请输入总金额" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>-->
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction, postAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import ErpGoodsListModel from '@comp/base/modal/ErpGoodsListModal'
import EditableCell from '@comp/table/EditableCell'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import EditoptionCell from '@/components/table/EditoptionCell.vue'
import { min } from 'xe-utils/methods'
import { GetExpandDictItem } from '../../../../utils/tslCommon'
import EditNumberCell2 from '../../../../components/table/EditNumberCell2.vue'

export default {
  name: 'BussContractRequirementReviewForm',
  components: {
    ErpGoodsListModel,
    EditableCell,
    EditoptionCell,
    EditNumberCell2,
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    dataId: {
      type: String,
    },
    models: {
      type: Object,
    },
    currency: {
      type: String,
    },
  },
  watch: {
    currency(newValue) {
      this.getLimit(newValue)
    },
    dataId(newValue) {
      this.getFormData(newValue)
    },


  },
  data() {
    return {
      packageDisabled: true,
      starterDisabled: true,
      financeDisabled: true,
      topLimit: 0,
      bottomList: 0,
      description: '出口业务报价单',
      modalWidth: 1000,
      category: '',
      model: {
        contractReviewId: '',
        erpGoodsPackageList: [],
        productQuotationList: [],
      },
      packageMethodOptions: [],
      codingFeeOptions: [],
      autoMidExpenseOptions: [],
      manualMidExpenseOptions: [],

      lab: 1,
      warpMaterial: {
        columns: [
          {
            title: '名称',
            dataIndex: 'name',
            width: 150,
          },
          {
            title: '规格',
            dataIndex: 'spec',
            // width: 100,
          },
          {
            title: '件/吨',
            dataIndex: 'ton',
            // width: 100,
          },
          {
            title: '规格',
            // width:202,
            children: [
              {
                title: '克数/毫升',
                dataIndex: 'grams',
                scopedSlots: { customRender: 'grams' },
                // width: 100,
              },
              {
                title: '个数',
                dataIndex: 'number',
                scopedSlots: { customRender: 'number' },
                // width: 100,
              },
            ],
          },
          {
            title: '外包装1',
            // width:310,
            children: [
              // {
              //   title: '面积',
              //   dataIndex: 'packageArea1',
              //   scopedSlots: { customRender: 'packageArea1' },
              //   width: 100,
              // },
              {
                title: '个数',
                dataIndex: 'packageNumber1',
                scopedSlots: { customRender: 'packageNumber1' },
                // width: 100,
              },
              {
                title: '单价',
                dataIndex: 'packageUnitPrice1',
                scopedSlots: { customRender: 'packageUnitPrice1' },
                // width: 100,
              },
              {
                title: '金额',
                dataIndex: 'packageAmount1',
                // width: 100,
              },
            ],
          },
          {
            title: '外包装2',
            // width:310,
            children: [
              // {
              //   title: '面积',
              //   dataIndex: 'packageArea2',
              //   scopedSlots: { customRender: 'packageArea2' },
              //   width: 100,
              // },
              {
                title: '个数',
                dataIndex: 'packageNumber2',
                scopedSlots: { customRender: 'packageNumber2' },
                // width: 100,
              },
              {
                title: '单价',
                dataIndex: 'packageUnitPrice2',
                scopedSlots: { customRender: 'packageUnitPrice2' },
                // width: 100,
              },
              {
                title: '金额',
                dataIndex: 'packageAmount2',
                // width: 100,
              },
            ],
          },
          {
            title: '内包装',
            // width:310,
            children: [
              // {
              //   title: '面积',
              //   dataIndex: 'innerPackageArea',
              //   scopedSlots: { customRender: 'innerPackageArea' },
              //   width: 100,
              // },
              {
                title: '个数',
                dataIndex: 'innerPackageNumber',
                scopedSlots: { customRender: 'innerPackageNumber' },
                // width: 100,
              },
              {
                title: '单价',
                dataIndex: 'innerPackageUnitPrice',
                scopedSlots: { customRender: 'innerPackageUnitPrice' },
                // width: 100,
              },
              {
                title: '金额',
                dataIndex: 'innerPackageAmount',
                // width: 100,
              },
            ],
          },
          {
            title: '其他',
            dataIndex: 'other',
            scopedSlots: { customRender: 'otherPackageCost' },
            // width: 100,
          },
          {
            title: '包装成本',
            dataIndex: 'packageCost',
            // width: 100,
          },
          {
            title: '操作',
            width: 80,
            dataIndex: 'operation',
            scopedSlots: { customRender: 'operation' },
          },
        ],
      },
      productQuote: {
        columns: [
          {
            title: '名称',
            dataIndex: 'name',
            width: 120,
          },
          {
            title: '规格',
            dataIndex: 'spec',
            width: 100,
          },
          {
            title: '最小单位克数(g)',
            dataIndex: 'packageSpec',
            width: 120,
            scopedSlots: { customRender: 'packageSpec' },
          },
          {
            title: '包装方式',
            dataIndex: 'packageMethod',
            width: 180,
            scopedSlots: { customRender: 'packageMethod' },
          },
          {
            title: '件/吨',
            width: 80,
            dataIndex: 'ton',
          },
          {
            title: '打码费',
            dataIndex: 'codingFee',
            width: 100,
            scopedSlots: { customRender: 'codingFee' },
          },
          {
            title: '原料',
            width: 100,
            dataIndex: 'material',
          },
          {
            title: '包材',
            width: 100,
            dataIndex: 'packageMaterials',
          },
          {
            title: '中间费用',
            width: 100,
            dataIndex: 'midExpenses',
            scopedSlots: { customRender: 'midExpenses' },
          },
          {
            title: '合计',
            width: 100,
            dataIndex: 'total',
          },
          {
            title: '出厂价',
            children: [
              {
                title: '*税率/汇率',
                width: 100,
                dataIndex: 'exWorksPrice',
              },
            ],
          },
          {
            title: '陆运费',
            width: 100,
            dataIndex: 'landFreight',
            scopedSlots: { customRender: 'landFreight' },
          },
          // {
          //   title: '不干胶贴',
          //   width: 100,
          //   dataIndex: 'adhesiveStickers',
          //   scopedSlots: { customRender: 'adhesiveStickers' },
          // },
          {
            title: '海运费',
            width: 100,
            dataIndex: 'seaFreight',
            scopedSlots: { customRender: 'seaFreight' },
          },
          {
            title: '认证费用',
            width: 100,
            dataIndex: 'cocoExpenses',
            scopedSlots: { customRender: 'cocoExpenses' },
          },
          // {
          //   title: '版费',
          //   width: 100,
          //   dataIndex: 'royalty',
          //   scopedSlots: { customRender: 'royalty' },
          // },
          {
            title: '保费',
            width: 100,
            dataIndex: 'insurancePremium',
            scopedSlots: { customRender: 'insurancePremium' },
          },
          // {
          //   title: '印刷费',
          //   width: 100,
          //   dataIndex: 'printingFee',
          //   scopedSlots: { customRender: 'printingFee' },
          // },
          {
            title: '佣金',
            width: 100,
            dataIndex: 'commission',
            scopedSlots: { customRender: 'commission' },
          },
          // {
          //   title: '其他2',
          //   width: 100,
          //   dataIndex: 'other2',
          //   scopedSlots: { customRender: 'other2' },
          // },
          {
            title: '其他',
            width: 100,
            dataIndex: 'other',
            scopedSlots: { customRender: 'other' },
          },
          {
            title: '合计',
            width: 100,
            dataIndex: 'total2',
          },
          {
            title: '业务员',
            children: [
              {
                title: '吨数',
                width: 100,
                dataIndex: 'ywTon',
              },
              // {
              //   title: '赔偿吨数',
              //   width: 120,
              //   dataIndex: 'ywDamageTon',
              //   scopedSlots: { customRender: 'ywDamageTon' },
              // },
              {
                title: '报价',
                dataIndex: 'ywTonPrice',
                width: 120,
                scopedSlots: { customRender: 'ywTonPrice' },
              },
              // {
              //   title: '件价',
              //   dataIndex: 'ywPiecePrice',
              // },
              // {
              //   title: '实际报价',
              //   width: 100,
              //   dataIndex: 'ywActualQuote',
              // },
              {
                title: '是否符合政策',
                width: 100,
                scopedSlots: { customRender: 'ywisCompliantPolicies' },
                dataIndex: 'ywisCompliantPolicies',
              },
            ],
          },
          {
            title: '操作',
            width: 80,
            dataIndex: 'operation',
            scopedSlots: { customRender: 'operation' },
          },
        ],
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
      labelCol3: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
      wrapperCol3: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
      confirmLoading: false,
      validatorRules: {
        code: [{ required: true, message: '请输入评审表编号!' }],
      },
      url: {
        add: '/business/bussOutletQuote/add',
        edit: '/business/bussOutletQuote/edit',
        queryById: '/business/bussOutletQuote/queryById',
      },
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    this.initDictConfig()
  },
  methods: {
    checkTaskDisabled(taskName) {
      console.log(taskName, '确认定价编辑')
      if (taskName) {
        if (taskName.indexOf('包材核价') > -1 || taskName == '毕翠霞') {
          this.packageDisabled = false
          console.log(taskName, '定义表单编辑===', this.packageDisabled && this.formDisabled)
        } else if (taskName == '总体审核') {
          this.financeDisabled = false
        } else if (taskName == '业务员最后更改') {
          this.starterDisabled = false
        }
      }
    },
    getFormData(newValue) {
      if (!newValue) {
        return
      }
      this.model.contractReviewId = newValue
      console.log(this.model.contractReviewId, '报价单数据获取')
      const that = this
      getAction('/business/bussOutletQuote/queryByReviewId', { id: newValue }).then((res) => {
        let erpGoodsList = res.result
        this.model = Object.assign({}, erpGoodsList)
        if (this.model.erpGoodsPackageList && this.model.erpGoodsPackageList.length > 0) {
          this.model.erpGoodsPackageList = res.result.erpGoodsPackageList.map((item) => {
            item = that.specCalc(item)
            return { ...item, rowKey: item.goodsId }
          })
        }
        if (this.model.productQuotationList && this.model.productQuotationList.length > 0) {
          this.model.productQuotationList = res.result.productQuotationList.map((item) => {
            return { ...item, rowKey: item.goodsId }
          })
        }
        console.log(res, '报价单数据获取结果')
      })
    },
    specCalc(item) {
      try {
        item.spec = item.spec.toUpperCase().trim()

        if (item.number && item.number > 0) {
          return item
        }
        if (item.grams && item.grams > 0 && item.ton && item.ton > 0) {
          //根据克数计算内包装数量和金额
          item.innerPackageNumber = (parseFloat(1000000.0) / parseFloat(item.grams)).toFixed(2)
          item.innerPackageAmount = parseFloat(
            item.innerPackageNumber * parseFloat(item.innerPackageUnitPrice)
          ).toFixed(2)
          item.number = (parseFloat(1000000.0) / parseFloat(item.grams) / parseFloat(item.ton)).toFixed(2)
          let tmp = parseFloat(item.grams) * parseFloat(item.number)
          if (tmp && tmp > 0) {
            item.packageNumber1 = (parseFloat(1000000) / parseFloat(tmp)).toFixed(2)
          }
        }
      } catch (e) {}
      console.log(item, '包材计算')
      return item
    },
    getLimit(currency) {
      console.log('根据币种获取超额上下限', currency)
      if (currency == '2') {
        GetExpandDictItem('PRICE_TOP_LIMIT_DOLLAR').then((res) => {
          this.topLimit = parseFloat(res.result.value)
        })
        GetExpandDictItem('PRICE_LOW_LIMIT_DOLLAR').then((res) => {
          this.bottomList = parseFloat(res.result.value) * -1
        })
      } else {
        GetExpandDictItem('PRICE_TOP_LIMIT_RMB').then((res) => {
          this.topLimit = parseFloat(res.result.value)
        })
        GetExpandDictItem('PRICE_LOW_LIMIT_RMB').then((res) => {
          this.bottomList = parseFloat(res.result.value) * -1
        })
      }
    },
    initDictConfig() {
      initDictOptions('package_method').then((res) => {
        if (res.success) {
          this.packageMethodOptions = res.result
        }
      })
      initDictOptions('coding_fee').then((res) => {
        if (res.success) {
          this.codingFeeOptions = res.result
        }
      })
      initDictOptions('auto_mid_expenses').then((res) => {
        if (res.success) {
          this.autoMidExpenseOptions = res.result
        }
      })
      initDictOptions('manual_mid_expenses').then((res) => {
        if (res.success) {
          this.manualMidExpenseOptions = res.result
        }
      })
    },
    tabsChange(activeKey) {
      this.tabs.activeKey = activeKey
    },
    getPfCode() {
      postAction('/sys/fillRule/executeRuleByCode/psbbh', {}).then((res) => {
        this.model.code = res.result
      })
    },
    add() {},
    edit(record) {
      this.model = Object.assign({}, record)
    },
    submitForm(id) {
      //提交
      const that = this
      this.model.contractReviewId = id
      if (!id) {
        that.$message.warning('请先保存合同评审表')
        return
      }
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                this.$emit('my-event', res.message)
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    addGoods: function (val) {
      this.lab = val
      this.$nextTick(() => {
        this.$refs.selectGoodsList.add()
      })
    },
    goodsOk(datas) {
      const _this = this
      //todo 产品关联配方有问题
      postAction('/base/erpGoods/list/ids', { ids: datas }).then((res) => {
        let erpGoodsList = res.result
        if (_this.lab == 1) {
          _this.pushPackage(erpGoodsList)
        } else {
          _this.pushProductPrice(erpGoodsList)
        }
      })
    },
    pushPackage(erpGoods) {
      const _this = this
      erpGoods.forEach(function (item, index) {
        let detail = {}
        detail.goodsId = item.id
        detail.name = item.name
        detail.noneSpec = item.noneSpec
        _this.filterPackageId(item.id, _this.model.erpGoodsPackageList)
        _this.model.erpGoodsPackageList.push(detail)
      })
    },
    pushProductPrice(erpGoods) {
      const _this = this
      erpGoods.forEach(function (item, index) {
        let detail = {}
        detail.goodsId = item.id
        detail.name = item.name
        detail.noneSpec = item.noneSpec
        _this.filterPackageId(item.id, _this.model.productQuotationList)
        _this.model.productQuotationList.push(detail)
      })
    },
    filterPackageId(goodsId, obj) {
      obj = obj.filter(function (item) {
        return item.goodsId !== goodsId
      })
    },
    calcMaterial(goodsId, materialFee) {
      const dataSource = [...this.model.productQuotationList]
      const target = dataSource.find((item) => item.goodsId === goodsId)
      if (target) {
        console.log('实时计算原料成本：', goodsId, materialFee)
        target.material = materialFee
        this.model.productQuotationList = dataSource
        this.calcFees(target)
      }
    },
    onProductCellChange(record, dataIndex, value) {
      const dataSource = [...this.model.productQuotationList]
      const target = dataSource.find((item) => item.goodsId === record.goodsId)
      if (record) {
        target[dataIndex] = value
        this.model.productQuotationList = dataSource
        this.calcFees(target, dataIndex)
      }
    },
    calcAllFees() {
      const datasource = [...this.model.productQuotationList]
      const that = this
      datasource.forEach((record) => {
        that.calcFees(record)
      })
    },
    calcFees(target, dataIndex) {
      const dataSource = [...this.model.productQuotationList]
      const newTarget = dataSource.find((item) => item.goodsId === target.goodsId)
      console.log(newTarget,"修改记录")
      if (dataIndex == 'packageMethod' || dataIndex == 'packageSpec' || dataIndex == 'codingFee') {
        console.log('计算中间费用', target)
        let addedFee = 0
        if (target.packageMethod && target.packageSpec) {
          const specNum = target.packageSpec
          const ton = target.ywTon

          if (target.packageMethod == '自动包装') {
            let defaultOption = this.autoMidExpenseOptions.filter((item) => item.text == '-')
            addedFee = Number.parseFloat(defaultOption[0].value)
            let valueInRange = this.findValueInRange(specNum, this.autoMidExpenseOptions)
            if (valueInRange) {
              addedFee = parseFloat(valueInRange)
            }
          } else if (target.packageMethod == '非自动包装') {
            //特殊部分
            let specialOption = this.manualMidExpenseOptions.filter((item) => item.text.startsWith('special'))
            let [specMax, tonMin] = this.parseRange(specialOption[0].text.slice(7))
            if (specialOption && specMax && tonMin && specNum >= specMax && ton > tonMin) {
              addedFee = parseFloat(specialOption[0].value)
            } else {
              let defaultOption = this.manualMidExpenseOptions.filter((item) => item.text == '-')
              addedFee = Number.parseFloat(defaultOption[0].value)
              let valueInRange = this.findValueInRange(specNum, this.autoMidExpenseOptions)
              if (valueInRange) {
                addedFee = parseFloat(valueInRange)
              }
            }
          }
          console.log('增加中间费用=', addedFee)
        }
        newTarget.midExpenses = parseFloat(target.codingFee) + parseFloat(addedFee)
        console.log('中间费用=', newTarget.midExpenses)
      }

      newTarget.material = newTarget.material ? newTarget.material : 0
      //成本合计
      newTarget.total = (
        parseFloat(newTarget.midExpenses) +
        parseFloat(newTarget.material) +
        parseFloat(newTarget.packageMaterials)
      ).toFixed(2)
      //出厂价
      this.model.exchangeRate = this.model.exchangeRate ? this.model.exchangeRate : 1
      this.model.rate = this.model.rate ? this.model.rate : 1
      newTarget.exWorksPrice = (
        (parseFloat(newTarget.total) * parseFloat(this.model.exchangeRate)) /
        parseFloat(this.model.rate)
      ).toFixed(2)

      //合计=出厂价+陆运费+不干胶+其他+海运费+COCO费用+版费+保费+印刷费+佣金+其他费用
      newTarget.total2 = (
        parseFloat(newTarget.exWorksPrice) +
        parseFloat(newTarget.landFreight) +
        parseFloat(newTarget.adhesiveStickers) +
        parseFloat(newTarget.other) +
        parseFloat(newTarget.seaFreight) +
        parseFloat(newTarget.cocoExpenses) +
        // parseFloat(newTarget.royalty) +
        parseFloat(newTarget.insurancePremium) +
        // parseFloat(newTarget.printingFee) +
        parseFloat(newTarget.commission) +
        parseFloat(newTarget.other2)
      ).toFixed(2)
      newTarget.ywActualQuote = newTarget.ywTonPrice //实际报价=报价
      //是否符合政策判断标准？
      let diff = parseFloat(newTarget.ywTonPrice) - parseFloat(newTarget.total2)
      if (diff > this.topLimit || diff < this.bottomLimit) {
        newTarget.ywisCompliantPolicies = '0'
      } else {
        newTarget.ywisCompliantPolicies = '1'
      }
      newTarget.rowKey = newTarget.goodsId + 1
      this.model.productQuotationList = dataSource
      //总金额
      let totalTonAmount = dataSource.reduce((sum, item) => {
        return sum + item.ywTon * item.ywTonPrice
      }, 0)
      console.log(totalTonAmount, '总费用计算')

      this.model.otherExpenses = this.model.otherExpenses ? this.model.otherExpenses : 0
      this.model.totalAmount = (parseFloat(this.model.otherExpenses) + totalTonAmount).toFixed(2)
      this.$forceUpdate()
    },
    findValueInRange(num, data) {
      for (let i = 0; i < data.length; i++) {
        let item = data[i]
        if (item.text.includes(',')) {
          let [min, max] = this.parseRange(item.text)
          if (num >= min && num < max) {
            return item.value
          }
        }
      }

      return null // Not found
    },
    parseRange(rangeText) {
      const [minStr, maxStr] = rangeText.slice(1, -1).split(',')
      let min = parseFloat(minStr)
      let max = parseFloat(maxStr)

      // Adjust for inclusive/exclusive endpoints
      if (rangeText.startsWith('[')) {
        min = min // Inclusive
      } else {
        min = min + 0.0000001 // Exclusive, add a tiny value to make it inclusive
      }

      if (rangeText.endsWith(']')) {
        max = max // Inclusive
      } else {
        max = max - 0.0000001 // Exclusive, subtract a tiny value to make it inclusive
      }

      return [min, max]
    },
    onCellChange(record, dataIndex, value) {
      const dataSource = [...this.model.erpGoodsPackageList]
      const target = dataSource.find((item) => item.goodsId === record.goodsId)
      if (record) {
        target[dataIndex] = value
        this.model.erpGoodsPackageList = dataSource
        if (dataIndex == 'grams') {
          target.number = (parseFloat(1000000.0) / parseFloat(target.grams) / parseFloat(target.ton)).toFixed(2)
        }
        this.calcPackageFees(target)
      }
    },
    calcPackageFees(target) {
      const dataSource = [...this.model.erpGoodsPackageList]
      const newTarget = dataSource.find((item) => item.goodsId === target.goodsId)
      if (newTarget.grams && newTarget.grams > 0) {
        //根据克数计算内包装数量和金额
        newTarget.innerPackageNumber = (parseFloat(1000000.0) / parseFloat(newTarget.grams)).toFixed(2)
        newTarget.innerPackageAmount = parseFloat(
          newTarget.innerPackageNumber * parseFloat(newTarget.innerPackageUnitPrice)
        ).toFixed(2)
      }

      let tmp = parseFloat(newTarget.grams) * parseFloat(newTarget.number)
      if (tmp && tmp > 0) {
        newTarget.packageNumber1 = (parseFloat(1000000) / parseFloat(tmp)).toFixed(2)
      }
      if (newTarget.packageNumber1 >= 0 && newTarget.packageUnitPrice1 >= 0) {
        //newTarget.ton = newTarget.packageNumber1
        newTarget.packageAmount1 = (
          parseFloat(newTarget.packageNumber1) * parseFloat(newTarget.packageUnitPrice1)
        ).toFixed(2)
      }

      newTarget.packageAmount2 = (
        parseFloat(newTarget.packageNumber2) * parseFloat(newTarget.packageUnitPrice2)
      ).toFixed(2)
      //成本
      newTarget.packageCost = (
        parseFloat(newTarget.packageAmount1) +
        parseFloat(newTarget.packageAmount2) +
        parseFloat(newTarget.innerPackageAmount) +
        parseFloat(newTarget.other)
      ).toFixed(2)

      newTarget.rowKey += 1
      this.erpGoodsPackageList = dataSource
      if (newTarget.packageCost && newTarget.packageCost > 0) {
        const pdataSource = [...this.model.productQuotationList]
        const pnewTarget = pdataSource.find((item) => item.goodsId === newTarget.goodsId)
        pnewTarget.packageMaterials = newTarget.packageCost
        this.model.productQuotationList = pdataSource
        this.calcFees(pnewTarget)
      }
    },
    onDelete(key) {
      const dataSource = [...this.model.erpGoodsPackageList]
      this.model.erpGoodsPackageList = dataSource.filter((item) => item.id !== key)
      // deleteAction('base/erpGoodsFormulaDetail/delete',{id:key}).then(res=>{
      //   if(res.success){
      //
      //   }
      // })
    },
    onDeleteProduct(key) {
      const dataSource = [...this.model.productQuotationList]
      this.model.productQuotationList = dataSource.filter((item) => item.id !== key)
      // deleteAction('base/erpGoodsFormulaDetail/delete',{id:key}).then(res=>{
      //   if(res.success){
      //
      //   }
      // })
    },
  },
}
</script>

<style lang="stylus" scoped>
.mytable >>> .ant-table-thead > tr > th, .ant-table-tbody > tr > td {
  padding: 2px 2px;
  overflow-wrap: break-word;
}
.mytable >>> .ant-table-tbody .ant-table-row td {
  padding-top: 2px;
  padding-bottom: 2px;
}
.mytable{
  .ant-table {
    min-height: 200px !important;
  }
}
</style>
